package cn.gson.crm.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.model.dao.CustomerDao;
import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.MessageDao;
import cn.gson.crm.model.entity.Customer;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.Message;
import cn.gson.crm.model.mapper.EmployeeMapper;

/**
 * 获客线索
 * @author Sirius
 *
 */
@Controller
@RequestMapping("cusleads")
public class CusLeadsController {

	@Autowired
	CustomerDao cusDao;
	
	@Autowired
	EmployeeDao empDao;
	
	
	@Autowired
	EmployeeMapper empMapper;
	
	@Autowired
	MessageDao messageDao;
	
	@RequestMapping
	public String init() {
		return "cusleads/cusleads";
	}
	
	//显示表格数据（只显示未处理的数据，不过得在页面上分为主管的显示和销售人员的显示）
	@PostMapping("list")
	@ResponseBody
	public Map<String, Object> list(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "10") int rows,HttpServletRequest req){
		Employee emp = (Employee)req.getSession().getAttribute("employee");
		//倒序排列，离当前日期近的放前面
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.DESC,"id"));
		Page<Customer> cusleads = null;
		//isDelete状态为false的才能显示出来，为true表明已删除
		//后面再添加，如果职位不同，那么就需要从session里将职位都取出来，再根据职位采用不同的find方法，对不同的职位显示不同的数据。
		//销售员显示所有与当前登录用户相关且未删除并且未处理的客户线索
		if (emp.getRole().getRoleName().equals("销售员")) {
			cusleads = cusDao.findAllByEmployeeAndIsDeleteAndSaState(emp,false,false,pr);
		}else {
			//管理者只需显示未分配的销售线索及未删除的
			cusleads = cusDao.findAllByMaStateAndIsDelete(false,false,pr);
		}
		Map<String, Object> data = new HashMap<>();
		data.put("rows", cusleads.getContent());
		data.put("total", cusleads.getTotalElements());
		return data;
	}
	
	
	/**
	 * 打开form表单
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"cusleadsform","cusleadsform/{id}"})
	public String cusForm(@PathVariable(required=false) Long id,Model model){
		//如果是编辑，则应该获取到id再填入相关信息
		if (id != null) {
			model.addAttribute("c",cusDao.findOne(id));
		}
		return "cusleads/cusleadsform";
	}
	
	
	
	/**
	 * 保存表单内容，新建和编辑时使用
	 * @param customer
	 * @param br
	 * @return
	 */	
	@RequestMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid Customer customer,Long empid,BindingResult br) {
		JSONObject result = new JSONObject();
		Employee emp = null;
		if (br.hasErrors()) {
			result.put("err", "校验失败！");
		}else {
			//如果empid不为空，说明是经理在处理，分配此获客线索给员工
			if (empid != null) {
				emp = empDao.findOne(empid);
				//需判断员工存在与否
				if (emp == null) {
					result.put("err", "此员工不存在！");
				}else {
					customer.setEmployee(emp);
					//分配好员工后，将经理处理状态改为true
					customer.setMaState(true);
				}
			}
			//如果是员工处理，则是选择生命周期,直接保存即可。
			if (customer.getLifecycle() != null) {
				//如果生命周期不为空，说明是员工在处理，将员工处理状态改为true
				customer.setSaState(true);
			}
			cusDao.save(customer);
/*			messageDao.save(new Message("获客线索", new Date(), null, "新获客线索", emp.getEmpName()+"添加一条新获客线索了！"));
*/			result.put("success", true);
			
		}
		return result;
	}
	
	/**
	 * 因为客户信息会关联比较多的外键
	 * 所以不在数据库删除此条信息
	 * 只是将是否删除（isDelete）这个字段改成true，代表已删除
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	public Map<String, Object> delete(@PathVariable Long id) {
		
		Map<String, Object> data = new HashMap<>();
		
		try {
			Customer customer = cusDao.findOne(id);
			customer.setDelete(true);
			cusDao.save(customer);
			data.put("success", true);
			
		} catch (Exception e) {
			e.printStackTrace();
			data.put("success", false);
			data.put("errorMsg", e.getMessage());
		}
		return data;
	}
	
	
	@PostMapping("search/{seacont}")
	@ResponseBody
	public List<Employee> search(@PathVariable String seacont){
		List<Employee> emps = new ArrayList<>();
		emps = empMapper.searchEmp(seacont);
		return emps;
	}
}
